<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * Main Controller
 * @author Babak Taraghi 'babak.taraghi@gmail.com'
 * @since September, 2011
 */
class Link extends CI_Controller {


	/**
	 * @desc Array - datas which should pass to the views
	 */
	var $data = array();



	/**
	 * @desc Controller Constructor
	 * This will check the session to see if the user is logged in or what
	 * And will load the related language files
	 */
	public function __construct(){
		parent::__construct();
	}




	/**
	 * @desc This will get called when no method specified
	 * Will show a welcome page
	 */
	public function index($from=0){
		
		$this->data["from"] = $from;
		
		$this->setInventory($from);
		$this->setForm();
		
		$this->load->view("cp/container",$this->data);
	}




	public function submit(){
		$title = trim($this->input->post("title"));
		$linkAddress = trim($this->input->post("link_address"));
		$desc = trim($this->input->post("description"));
		$enable = ($this->input->post("enable")) ? "1" : "0";
		$id = trim($this->input->post("id"));

		$config['allowed_types'] = "*";
		//$config['upload_path'] = getcwd().'\\files\\uploads\\'; // windows
		$config['upload_path'] = 'files/uploads'; // linux (remember to chmod this)

		if(empty($title) || empty($desc)){

			$this->data["formErrors"][] = "Required fields are empty.";
		}else{
			$this->load->helper('date');
			
			$fieldsValues = array(
				"title"=>$title,
				"link_address"=>$linkAddress,
				"description"=>$desc,
				"enable"=>$enable,
			);
			
			$this->load->model("link_model","linkModel");
			$this->load->library('upload', $config);
				
			if(isset($_FILES["image"]) && !empty($_FILES["image"]["name"])){

				if ( ! $this->upload->do_upload("image")){
					
					$this->data["formErrors"][] = $this->upload->display_errors();
					return $this->index();
				}else{
					
					$imageData = $this->upload->data();
					$fieldsValues["image"] = $imageData["file_name"];
				}
			}

			if($id){
				
				$result = $this->linkModel->update($id, $fieldsValues);
				
				if($result){
					$this->data["formMessages"][] = "Ok. Record updated.";
				}else{
					$this->data["formErrors"][] = "Faild.";
				}
				
			}else{
				
				$result = $this->linkModel->insert($fieldsValues);
				
				if($result){
					$this->data["formMessages"][] = "Ok. New record saved.";
				}else{
					$this->data["formErrors"][] = "Faild.";
				}
			}
				
		}
		
		$this->index();
	}



	public function setInventory($from){
		
		$this->load->model("link_model","linkModel");
		$this->load->helper("form");
		
		$totalRecs = $this->linkModel->getTotalRecordsNumber();
		$recsPerPage = 15;
		$uriSegment = "4";
		$extraURL = "";
		
		
		$this->setPagingLinks($totalRecs, $recsPerPage, $uriSegment, $extraURL);
		
		$this->data["items"] = $this->linkModel->getRecords("",$from,$recsPerPage);
		
		if (isset($this->data["content"])){
			$this->data["content"] .= $this->load->view("cp/list_link",$this->data,TRUE);
		}else{
			$this->data["content"] = $this->load->view("cp/list_link",$this->data,TRUE);
		}
	}




	/**
	 * @desc This will set pagination links html to the $this->data field.
	 * @param Integer 'totalRecs' is the number of total records of the table
	 * @param Integer 'recsPerPage' indicates how many of records of the table should list in a page
	 * @param Integer 'uriSegment' which part of url indicates page number
	 * @param String 'extraURL' the url (method and modelname)that should get called after a page clicked
	 */
	private function setPagingLinks($totalRecs,$recsPerPage,$uriSegment,$extraURL){
		$this->load->library('pagination');
		$config = array(
			'base_url'=>site_url("cp/links/$extraURL"),
			'total_rows'=> $totalRecs,
			'per_page'=> $recsPerPage,
			"uri_segment"=>$uriSegment,
			"num_links"=>3,
			"full_tag_open"=>"<center>",
			"full_tag_close"=>"</center>",
			"first_link"=>$this->lang->line("firstPage"),
			"first_tag_open"=>"<div class='firstPage'>",
			"first_tag_close"=>"</div>",
			"last_link"=>$this->lang->line("lastPage"),
			"last_tag_open"=>"<div class='firstPage'>",
			"last_tag_close"=>"</div>",
			"next_tag_open"=>"<div class='page'>",
			"next_tag_close"=>"</div>",
			"prev_tag_open"=>"<div class='page'>",
			"prev_tag_close"=>"</div>",
			"num_tag_open"=>"<div class='page'>",
			"num_tag_close"=>"</div>",
			'cur_tag_open'=>"<div class='currentPage'>",
			'cur_tag_close'=>"</div>"
		);
		$this->pagination->initialize($config);
		$this->data["pagination"] = $this->pagination->create_links();
	}




	/**
	 * @desc This will delete records of table
	 * @param Array $_POST 'ids' ids of records which should delete
	 */
	public function delete($from=0){
		$this->load->model("link_model","linkModel");
		
		$ids = $this->input->post("ids");
		
		foreach($ids as $k=>$id){
			if($id > 1){
				$record = $this->linkModel->getRecord("id",$id);
				@unlink("files/uploads/".$record->image);
				@unlink("files/uploads/".$record->movie);
				
				$filename = explode(".",$record->image);
				$name = "";
				foreach($filename as $key=>$part){
					if(count($filename) != $key+1){
						$name .= $part;
					}else{
						$ext = $part;
					}
				}

				// remembet ro change this if thumbnails width or height changed
				@unlink("files/uploads/thumbs/".$name."-0-100.".$ext);
				@unlink("files/uploads/thumbs/".$name."-200-0.".$ext);
			}
		}
		
		$result = $this->linkModel->delete($ids);
		
		if($result){
			$this->data["listMessages"][] = "Ok. Record(s) deleted.";
		}else{
			$this->data["listErrors"][] = "Faild.";
		}
		
		$this->index($from);
	}


	
	
	
	
	
	
	
	
	
	
	public function edit($id){
		
		$this->load->model("link_model","linkModel");
		$editItem = $this->linkModel->getRecord("id",$id);
		
		if(isset($editItem->image) && ! empty($editItem->image)){
			
			$this->load->helper("simple_image");
			$SI = new SimpleImage();
			$editItem->image = $SI->getThumbPathWidthHeight($editItem->image,0,100);
		}
		
		$this->data["editItem"] = $editItem;
		
		$this->index();
	}


	
	
	
	
	
	
	
	
	
	

	private function setForm(){
		
		$this->load->helper("form");
		
		if(isset($this->data["content"])){
			$this->data["content"] .= $this->load->view("cp/form_link",$this->data,TRUE);
		}else{
			$this->data["content"] = $this->load->view("cp/form_link",$this->data,TRUE);
		}
	}


}